﻿using Common;
using IdentityModel;
using IdentityServer4.Validation;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using SystemEntity;
using SystemService;

namespace Gateway.Identity
{
    /// <summary>
    /// 密码验证
    /// </summary>
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            try
            {
                string userName = context.UserName;
                string password = context.Password;
                string clientid = context.Request.ClientId;
                string SessionId = context.Request.SessionId;
                SystemUserService systemUserService = Application.GetService<SystemUserService>();

                SystemUserEntity userEntity = systemUserService.Validate(userName, password, clientid);

                if (userEntity == null)
                {
                    //验证异常结果
                    context.Result = new GrantValidationResult()
                    {
                        IsError = true,
                        Error = "用户名或密码错误",
                        //ErrorDescription = "用户名密码错误",
                        CustomResponse = new Dictionary<string, object>() { { "Error", "用户名或密码错误" }, { "IsError", "True" } }                         
                    };
                    return;
                }

                List<Claim> claimList = new List<Claim>()
                {
                    //new Claim(ClaimTypes.Name, $"{userName}"),
                    //new Claim(ClaimTypes.System, $"{clientid}"),
                    //new Claim(ClaimTypes.NameIdentifier, $"{userName}"),
                    new Claim(JwtClaimTypes.Subject, $"{userName}"),
                    new Claim(JwtClaimTypes.AuthenticationTime, $"{DateTimeOffset.Now.AddHours(8).ToUnixTimeSeconds()}"),
                    new Claim(JwtClaimTypes.IdentityProvider, $"{clientid}"),
                    new Claim(JwtClaimTypes.Name, $"{userName}"),
                    new Claim(JwtClaimTypes.JwtId, $"{userEntity.Id}"),
                    new Claim(JwtClaimTypes.NickName, $"{userEntity.NickName}"),
                    //new Claim(JwtClaimTypes.NickName, $"{userEntity.NickName}"),
                    //new Claim(JwtClaimTypes.NickName, $"{userEntity.NickName}"),
                };

                ClaimsIdentity claimsIdentity = new ClaimsIdentity(claimList.ToArray(), null, ClaimTypes.Name, null);
                // 验证账号
                context.Result = new GrantValidationResult
                (
                    subject: userName,
                    authenticationMethod: "ValidateAsync",
                    claims: claimList.ToArray()                     
                )
                { Subject = new ClaimsPrincipal(claimsIdentity) , CustomResponse = new Dictionary<string, object>() { { "IsError", "False" } } };
                context.UserName = userName;
            }
            catch (Exception ex)
            {
                //验证异常结果
                context.Result = new GrantValidationResult()
                {
                    IsError = true,
                    Error = ex.Message,
                    CustomResponse = new Dictionary<string, object>() { { "Error", ex.Message }, { "IsError", "True" } }
                };
            }
        }
    }
}
